<template>
  <!-- 轮播图 -->
  <el-carousel class="light" indicator-position="outside">
    <el-carousel-item
      v-for="(item, index) in carouselItems"
      :key="index"
      style="height: 400px"
    >
      <img
        :src="item.src"
        style="height: 400px; width: 1250px; object-fit: cover"
      />
      <h3 text="2xl" justify="center">{{ item.text }}</h3>
    </el-carousel-item>
  </el-carousel>
  <div class="container">
    <!-- 折线图和公告栏容器 -->
    <el-row
      class="content-row"
      :gutter="20"
      style="margin-top: 20px; margin-left: 20px"
    >
      <!-- 折线图模块 -->
      <el-col :span="16">
        <div class="module chart-module">
          <el-card class="module-card">
            <div class="module-title">每月用电和用水统计</div>
            <div ref="lineChart" class="chart" style="margin-top: 20px"></div>
          </el-card>
        </div>
      </el-col>

      <!-- 公告栏模块 -->
      <el-col :span="8">
        <div class="module announcement-module">
          <el-card class="module-card">
            <div class="module-title">公告栏</div>
            <router-link to="/message" class="more-link">
              查看更多
            </router-link>
            <el-timeline>
              <el-timeline-item
                v-for="(announcement, index) in announcements"
                :key="announcement.id"
                :timestamp="announcement.adTime"
              >
                {{ announcement.title }}
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.container {
  margin-top: 500px;
}
.light {
  position: absolute;
  margin-top: 50px;
  margin-left: 250px;
  width: 1250px;
  height: 400px;
}

.el-carousel__item h3 {
  color: #c45656;
  opacity: 0.75;
  display: flex;
  align-items: center;
  margin: 0;
  text-align: center;
  height: 100%;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.content-row {
  margin-top: 500px;
}

.module {
  border: 1px solid #fff; /* 模块边框 */
  padding: 10px;
  margin: 0 10px; /* 模块间距 */
}

.module-title {
  text-align: left; /* 模块标题左对齐 */
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.chart {
  width: 850px;
  height: 385px;
}

.el-timeline-item__content {
  text-align: left; /* 公告内容左对齐 */
}

.chart-module .module-card {
  width: 100%; /* 占满容器宽度 */
}

.announcement-module .module-card {
  width: 100%; /* 占满容器宽度 */
  height: 470px;
}
</style>

<script lang="ts">
import { defineComponent, ref, onMounted, reactive } from "vue";
import axios from "axios";
import * as echarts from "echarts";
import { computed } from "vue";

interface User {
  ordId: string;
  userId: string;
  realname: string;
  usedWater: string;
  waSum: string;
  usedElc: string;
  elSum: string;
  sum: string;
  addtime: string;
}

export default defineComponent({
  name: "LineChart",
  setup() {
    // 声明响应式数据
    const data = reactive({
      home: {
        ordId: "",
        userId: "",
        realname: "",
        usedWater: "",
        waSum: "",
        usedElc: "",
        elSum: "",
        sum: "",
        addtime: "",
      },
      homes: [] as User[],
    });

    // 轮播图数据
    const carouselItems = ref([
      {
        src: "C:\\Users\\10616\\Desktop\\xmsx\\frontend\\sbb\\src\\assets\\mt.jpg",
        text: "轮播图1",
      },
      {
        src: "C:\\Users\\10616\\Desktop\\xmsx\\frontend\\sbb\\src\\assets\\gpt.png",
        text: "轮播图2",
      },
      {
        src: "C:\\Users\\10616\\Desktop\\xmsx\\frontend\\sbb\\src\\assets\\error.png",
        text: "轮播图3",
      },
      {
        src: "C:\\Users\\10616\\Desktop\\xmsx\\frontend\\sbb\\src\\assets\\blue.png",
        text: "轮播图4",
      },
    ]);

    // ECharts 图表实例
    const lineChart = ref(null);
    
    // 从后端获取的公告数据
    const announcements = ref([]);
    const tableData = ref([]);
    const language = ref("zh-cn");
    const locale = computed(() => (language.value === "zh-cn" ? zhCn : en));
    const search = ref("");
    const displayData = computed(() => {
      return tableData.value.slice(0, 4); // 只显示前4条数据
    });
    const currentPage = ref(1);
    const pageSize = ref(10); // 每页显示10条数据
    const total = ref(0);
    const lastCheckTime = ref(new Date().toISOString());

    const toggle = () => {
      language.value = language.value === "zh-cn" ? "en" : "zh-cn";
    };

    // 初始化图表的函数
    const initChart = async () => {
      const chart = echarts.init(lineChart.value);

      // 获取数据
      const response = await axios.get("http://localhost:8080/home", {
        params: {
          userId: JSON.parse(localStorage.getItem("user") || "{}").userId,
        },
      });

      // 假设后端返回的数据结构中包含 homes 数组
      const homes = response.data;

      // 获取当前月份
      const currentMonth = new Date().getMonth() + 1;

      // 处理数据，确保每月1日的 addtime 数据显示的是上一个月的用电量和用水量数据
      const lineChartData = homes
        .filter((home: User) => {
          const month = parseInt(home.addtime.substring(5, 7));
          return month < currentMonth; // 只显示当前月份之前的完整月份的数据
        })
        .map((home: User) => ({
          month: home.addtime.substring(5, 7) + "月",
          usedElc: home.usedElc,
          usedWater: home.usedWater,
        }));

      // 按月份排序
      lineChartData.sort((a, b) => parseInt(a.month) - parseInt(b.month));

      // 提取数据
      const months = lineChartData.map((data) => data.month);
      const usedElcData = lineChartData.map((data) => data.usedElc);
      const usedWaterData = lineChartData.map((data) => data.usedWater);

      const option = {
        title: {
          text: "",
        },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["用电量", "用水量"],
        },
        xAxis: {
          type: "category",
          data: months, // 显示月份数据
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: "用电量",
            type: "line",
            data: usedElcData, // 使用从API获取的数据
            itemStyle: {
              color: "#5470C6", // 用电量线的颜色
            },
          },
          {
            name: "用水量",
            type: "line",
            data: usedWaterData, // 使用从API获取的数据
            itemStyle: {
              color: "#91CC75", // 用水量线的颜色
            },
          },
        ],
      };
      chart.setOption(option);
    };

    // 从后端获取数据的函数
    const fetchData = async () => {
      try {
        const response = await axios.get(
          "http://localhost:8080/user/allnoticeList",
          {
            params: {
              page: currentPage.value,
              size: pageSize.value,
              limit:4,
              search: search.value,
              includeAdmin: true,
            },
          }
        );
        announcements.value = response.data.data.records;
        tableData.value = response.data.data.records;
        total.value = response.data.data.total;
      } catch (error) {
        console.error("Failed to fetch data:", error);
      }
    };

    // 在组件挂载后初始化图表和获取数据
    onMounted(() => {
      initChart();
      fetchData();
    });

    // 返回响应式数据和方法，以供模板使用
    return {
      data,
      carouselItems,
      lineChart,
      initChart,
      announcements,
      tableData,
      language,
      search,
      currentPage,
      pageSize,
      total,
      lastCheckTime,
      toggle,
    };
  },
});
</script>